/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.dictionary;

import com.google.common.base.Strings;
import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.dd.DicCache;
import com.je.meta.cache.dd.DicQuickCache;
import com.je.meta.service.common.MetaDevelopLogService;
import com.je.meta.service.dictionary.DictionaryItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 数据字典项管理
 */
@RestController
@RequestMapping(value = "/je/meta/dictionary/item")
public class DictionaryItemController extends AbstractPlatformController {

    private static final Logger logger = LoggerFactory.getLogger(DictionaryItemController.class);

    @Autowired
    private MetaDevelopLogService developLogService;
    @Autowired
    private DicCache dicCache;
    @Autowired
    private DicQuickCache dicQuickCache;
    @Autowired
    private DictionaryItemService dictionaryItemService;

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        DynaBean dictionary = metaService.selectOneByPk("JE_CORE_DICTIONARY", dynaBean.getStr("DICTIONARYITEM_DICTIONARY_ID"),
                "JE_CORE_DICTIONARY_ID,DICTIONARY_DDNAME,DICTIONARY_DDCODE,DICTIONARY_DDTYPE");
        if (dictionary != null && (DDType.LIST.equals(dictionary.getStr("DICTIONARY_DDTYPE")) || DDType.TREE.equals(dictionary.getStr("DICTIONARY_DDTYPE")))) {
            removeDictionaryCache(dictionary);
        }
        if (dictionary != null) {
            developLogService.doDevelopLog("UPDATE", "修改", "DIC", "数据字典", dictionary.getStr("DICTIONARY_DDNAME"), dictionary.getStr("DICTIONARY_DDCODE"), dictionary.getStr("JE_CORE_DICTIONARY_ID"),dictionary.getStr("SY_PRODUCT_ID"));
        }
        return super.doSave(param, request);
    }

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        DynaBean dictionary = metaService.selectOneByPk("JE_CORE_DICTIONARY", dynaBean.getStr("DICTIONARYITEM_DICTIONARY_ID"), "JE_CORE_DICTIONARY_ID,DICTIONARY_DDNAME,DICTIONARY_DDCODE,DICTIONARY_DDTYPE");
        if (dictionary != null && (DDType.LIST.equals(dictionary.getStr("DICTIONARY_DDTYPE")) || DDType.TREE.equals(dictionary.getStr("DICTIONARY_DDTYPE")))) {
            removeDictionaryCache(dictionary);
        }
        if (dictionary != null) {
            developLogService.doDevelopLog("UPDATE", "修改", "DIC", "数据字典", dictionary.getStr("DICTIONARY_DDNAME"), dictionary.getStr("DICTIONARY_DDCODE"), dictionary.getStr("JE_CORE_DICTIONARY_ID"),dictionary.getStr("SY_PRODUCT_ID"));
        }
        return super.doUpdate(param, request);
    }

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        String funcType = getStringParameter(request, "funcType");
        String funcCode = getStringParameter(request, "funcCode");
        String codeGenFieldInfo = param.getCodeGenFieldInfo();
        Map<String, Object> map = dictionaryItemService.doUpdateList(param.getTableCode(), param.getStrData(), funcType, funcCode, codeGenFieldInfo);
        return BaseRespResult.successResult(map);
    }

    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        param.setTableCode("JE_CORE_DICTIONARYITEM");
        param.setFuncCode("JE_CORE_DICTIONARYITEM");
        if (StringUtil.isNotEmpty(ids)) {
            List<DynaBean> items = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder()
                    .in("JE_CORE_DICTIONARYITEM_ID", ids.split(",")), "JE_CORE_DICTIONARYITEM_ID,DICTIONARYITEM_DICTIONARY_ID");
            DynaBean item = items.iterator().next();
            DynaBean dictionary = metaService.selectOneByPk("JE_CORE_DICTIONARY", item.getStr("DICTIONARYITEM_DICTIONARY_ID"), "JE_CORE_DICTIONARY_ID,DICTIONARY_DDNAME,DICTIONARY_DDCODE,DICTIONARY_DDTYPE");
            if (dictionary != null && (DDType.LIST.equals(dictionary.getStr("DICTIONARY_DDTYPE")) || DDType.TREE.equals(dictionary.getStr("DICTIONARY_DDTYPE")))) {
                removeDictionaryCache(dictionary);
            }
            if (dictionary != null) {
                logger.info(SecurityUserHolder.getCurrentAccountName() + ": delete dicItem[DdItemController.doRemove] - [" + dictionary.getStr("DICTIONARY_DDCODE") + "]");
                developLogService.doDevelopLog("UPDATE", "修改", "DIC", "数据字典", dictionary.getStr("DICTIONARY_DDNAME"), dictionary.getStr("DICTIONARY_DDCODE"), dictionary.getStr("JE_CORE_DICTIONARY_ID"),dictionary.getStr("SY_PRODUCT_ID"));
            }
        }
        return super.doRemove(param, request);
    }

    /**
     * 检查字段项编码重复 提示重复名称和编码
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/checkDdItems", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkDdItems(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = param.getPkValue();
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult("字典ID不能为空！");
        }

        List<DynaBean> items = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder()
                .eq("DICTIONARYITEM_DICTIONARY_ID", pkValue)
                .ne("SY_NODETYPE", "ROOT")
                .ne("SY_PARENT", ""));
        String errors = "";
        Set<String> itemCodes = new HashSet();
        for (DynaBean item : items) {
            String itemCode = item.getStr("DICTIONARYITEM_ITEMCODE");
            if (StringUtil.isEmpty(itemCode)) {
                errors = "字典项【" + item.getStr("DICTIONARYITEM_ITEMCODE") + "】编码为空，请检查！";
                break;
            }
            if (itemCodes.contains(itemCode)) {
                errors = "字典项【" + item.getStr("DICTIONARYITEM_ITEMCODE") + "】编码重复，请修改！";
                break;
            }
            itemCodes.add(itemCode);
        }

        if (StringUtil.isNotEmpty(errors)) {
            return BaseRespResult.errorResult(errors);
        }

        return BaseRespResult.successResult(null, MessageUtils.getMessage("dictionary.item.licit"));
    }

    /**
     * 检查字段项编码重复 提示重复名称和编码
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/beforeSaveCheckDdItems", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult beforeSaveCheckDdItems(BaseMethodArgument param, HttpServletRequest request) {
        String codes = getStringParameter(request, "codes");
        String changeIds = getStringParameter(request, "changeIds");
        String pkValue = param.getPkValue();
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult("字典ID不能为空！");
        }
        List<DynaBean> items = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder()
                .eq("DICTIONARYITEM_DICTIONARY_ID", pkValue)
                .ne("SY_NODETYPE", "ROOT")
                .ne("SY_PARENT", ""));
        String errors = "";
        if (Strings.isNullOrEmpty(codes)) {
            List<String> codeList = new ArrayList<>();
            for (DynaBean item : items) {
                String itemCode = item.getStr("DICTIONARYITEM_ITEMCODE");
                if (codeList.contains(itemCode)){
                    errors = "字典项【" + itemCode + "】编码重复，请修改！";
                    return BaseRespResult.errorResult(errors);
                }
                codeList.add(itemCode);
            }
        }else {
            items = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder()
                    .eq("DICTIONARYITEM_DICTIONARY_ID", pkValue)
                    .ne("SY_NODETYPE", "ROOT")
                    .ne("SY_PARENT", "")
                    .notIn("JE_CORE_DICTIONARYITEM_ID",Arrays.asList(changeIds.split(","))));
            String[] codeSplit = codes.split(",");
            for (String code : codeSplit) {
                for (DynaBean item : items) {
                    String itemCode = item.getStr("DICTIONARYITEM_ITEMCODE");
                    if (!Strings.isNullOrEmpty(itemCode) && code.equals(itemCode)) {
                        errors = "字典项【" + item.getStr("DICTIONARYITEM_ITEMCODE") + "】编码重复，请修改！";
                        return BaseRespResult.errorResult(errors);
                    }
                }
            }
        }
        return BaseRespResult.successResult(null, MessageUtils.getMessage("dictionary.item.licit"));
    }


    private void removeDictionaryCache(DynaBean dictionary) {
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (Strings.isNullOrEmpty(currentTenantId)) {
            dicCache.removeCache(currentTenantId, dictionary.getStr("DICTIONARY_DDCODE"));
        }
        dicCache.removeCache(dictionary.getStr("DICTIONARY_DDCODE"));
        dicQuickCache.removeCache(dictionary.getStr("DICTIONARY_DDCODE"));
    }

}
